package com.yungam.imcs.controller.alarm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.yungam.common.bean.alarm.AlarmDto;
import com.yungam.common.bean.alarm.AlarmSolveLog;
import com.yungam.common.response.RetDTO;
import com.yungam.common.service.AlarmService;
import com.yungam.common.service.AlarmSolveLogService;
import com.yungam.common.service.UserService;
import com.yungam.common.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api(tags = "告警接口")
@RestController
@RequestMapping("/alarm")
public class AlarmController {
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private AlarmService alarmService;
    @Resource
    private DateUtils dateUtils;
    @Resource
    private AlarmSolveLogService alarmSolveLogService;
    @Resource
    private UserService userService;

    @ApiOperation("获取告警页面表格数据")
    @GetMapping("/tableData")
    public RetDTO<?> getTableData(@ApiParam("开始时间") String start,
                                  @ApiParam("结束时间") String end) throws ParseException {
        QueryWrapper<AlarmDto> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("timestamp");

        if (StringUtils.isNotEmpty(start) && StringUtils.isNotEmpty(end)) {
            long min = sdf.parse(start).getTime(), max = sdf.parse(end).getTime();
            queryWrapper.between("timestamp", min, max);
        }

        List<AlarmDto> list = alarmService.list(queryWrapper);
        // 整合处理人员信息 (if operator_id != null)
        for (AlarmDto dto : list) {
            if (dto.getOperatorId() != null) dto.setOperator(userService.getById(dto.getOperatorId()));
        }
        return RetDTO.data(list);
    }

    @ApiOperation("分页获取告警页面表格数据")
    @GetMapping("/tableDataByPage")
    public RetDTO<?> getTableDataByPage(@ApiParam("开始时间") String start,
                                        @ApiParam("结束时间") String end,
                                        @ApiParam("告警状态") @RequestParam(required = false) Integer state,
                                        @ApiParam("告警等级") @RequestParam(required = false) Integer level,
                                        @ApiParam("页号") @RequestParam(required = true) int pageNum,
                                        @ApiParam("每页数量") @RequestParam(required = true) int pageSize) throws ParseException {
        QueryWrapper<AlarmDto> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("timestamp");

        if (StringUtils.isNotEmpty(start) && StringUtils.isNotEmpty(end)) {
            long min = sdf.parse(start).getTime(), max = sdf.parse(end).getTime();
            queryWrapper.between("timestamp", min, max);
        }

        if (level != null) {
            queryWrapper.eq("level", level);
        }

        if (state != null) {
            queryWrapper.eq("state", state);
        }

        IPage<AlarmDto> page = new Page<>(pageNum, pageSize);
        page = alarmService.page(page, queryWrapper);
        List<AlarmDto> list = page.getRecords();

        // 整合处理人员信息 (if operator_id != null)
        for (AlarmDto dto : list) {
            if (dto.getOperatorId() != null) dto.setOperator(userService.getById(dto.getOperatorId()));
        }
        return RetDTO.data(page);
    }

    @ApiOperation("获取topBar栏中的未处理告警信息")
    @GetMapping("/topBarAlarmData")
    public RetDTO<?> getTopBarAlarmData() throws ParseException {
        String[] now = dateUtils.getTodayRange();
        if (now.length == 0) return RetDTO.data(Lists.newArrayList());
        long min = sdf.parse(now[0]).getTime(), max = sdf.parse(now[1]).getTime();
        List<AlarmDto> list = alarmService.list(new QueryWrapper<AlarmDto>().orderByDesc("timestamp")
                .between("timestamp", min, max).eq("state", 0));
        return RetDTO.data(list);
    }

    @ApiOperation("获取首页今日告警数据")
    @GetMapping("/dashboardAlarmData")
    public RetDTO<?> getDashboardAlarmData() throws ParseException {
        String[] now = dateUtils.getTodayRange();
        long min = sdf.parse(now[0]).getTime(), max = sdf.parse(now[1]).getTime();
        List<AlarmDto> list = alarmService.list(new QueryWrapper<AlarmDto>().orderByDesc("timestamp")
                .between("timestamp", min, max));
        return RetDTO.data(list);
    }

    @ApiOperation("处理告警")
    @PostMapping("/solve")
    public RetDTO<?> solve(@ApiParam("{alarmId: 告警id, userId: 用户id, remark: 备注}") @RequestBody Map<String, Object> data) {
        Integer alarmId = (Integer) data.get("alarmId"),
                userId = (Integer) data.get("userId");
        String remark = String.valueOf(data.get("remark"));

        AlarmSolveLog asl = new AlarmSolveLog();
        asl.setAlarmId(alarmId)
                .setRemark(remark)
                .setCreateTime(new Date());
        alarmSolveLogService.save(asl);
        // 更新 alarm 表
        AlarmDto alarm = alarmService.getById(alarmId);
        alarm.setState(1)
            .setOperatorId(userId)
            .setOperateTime(new Date());
        alarmService.updateById(alarm);

        return RetDTO.success();
    }

    @ApiOperation("查询今日处理告警的日志")
    @GetMapping("/solveLogs")
    public RetDTO<?> getSolveLogs() {
        String[] range = dateUtils.getTodayRange();
        List<AlarmSolveLog> list = alarmSolveLogService.list(new QueryWrapper<AlarmSolveLog>()
                .between("create_time", range[0], range[1]));

        for (AlarmSolveLog asl : list) {
            AlarmDto dto = alarmService.getById(asl.getAlarmId());
            dto.setOperator(userService.getById(dto.getOperatorId()));
            asl.setAlarmDto(dto);
        }
        return RetDTO.data(list);
    }

    /**
     * 一键处理告警
     */
    @ApiOperation("一键处理告警")
    @PostMapping("/solveAll")
    public RetDTO<?> solveAll(@ApiParam("{idList: 告警id, userId: 用户id, remark: 备注}") @RequestBody Map<String, Object> data) {
        List<Integer> idList = (List<Integer>) data.get("idList");
        Integer userId = (Integer) data.get("userId");
        String remark = String.valueOf(data.get("remark"));

        List<AlarmSolveLog> logs = Lists.newArrayList();
        List<AlarmDto> alarms = Lists.newArrayList();
        for (Integer alarmId : idList) {
            AlarmSolveLog asl = new AlarmSolveLog();
            asl.setAlarmId(alarmId)
                    .setRemark(remark)
                    .setCreateTime(new Date());
            logs.add(asl);

            AlarmDto alarm = new AlarmDto();
            alarm.setId(alarmId)
                    .setState(1)
                    .setOperatorId(userId)
                    .setOperateTime(new Date());
            alarms.add(alarm);
        }
        alarmSolveLogService.saveBatch(logs);
        // 更新 alarm 表
        alarmService.updateBatchById(alarms);

        return RetDTO.success();
    }

}
